~sircmpwn/paste.sr.ht

paste.sr.ht/api/server.go -rw-r--r-- 1.8 KiB
28102cc5Conrad Hoffmann Add api-origin to example config 12 days ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package main

import (
	"context"
	"database/sql"
	"net/http"

	"git.sr.ht/~sircmpwn/core-go/config"
	"git.sr.ht/~sircmpwn/core-go/database"
	"git.sr.ht/~sircmpwn/core-go/server"
	"github.com/99designs/gqlgen/graphql"
	"github.com/go-chi/chi"

	"git.sr.ht/~sircmpwn/paste.sr.ht/api/graph"
	"git.sr.ht/~sircmpwn/paste.sr.ht/api/graph/api"
	"git.sr.ht/~sircmpwn/paste.sr.ht/api/graph/model"
	"git.sr.ht/~sircmpwn/paste.sr.ht/api/loaders"
)

func main() {
	appConfig := config.LoadConfig(":5111")

	gqlConfig := api.Config{Resolvers: &graph.Resolver{}}
	gqlConfig.Directives.Access = func(ctx context.Context, obj interface{},
		next graphql.Resolver, scope model.AccessScope,
		kind model.AccessKind) (interface{}, error) {
		return server.Access(ctx, obj, next, scope.String(), kind.String())
	}
	schema := api.NewExecutableSchema(gqlConfig)

	scopes := make([]string, len(model.AllAccessScope))
	for i, s := range model.AllAccessScope {
		scopes[i] = s.String()
	}

	gsrv := server.NewServer("paste.sr.ht", appConfig).
		WithDefaultMiddleware().
		WithMiddleware(loaders.Middleware).
		WithSchema(schema, scopes)

	// Bulk transfer endpoints
	gsrv.Router().Get("/query/blob/{id}", func(w http.ResponseWriter, r *http.Request) {
		id := chi.URLParam(r, "id")
		if err := database.WithTx(r.Context(), &sql.TxOptions{
			Isolation: 0,
			ReadOnly:  true,
		}, func(tx *sql.Tx) error {
			var data []byte
			row := tx.QueryRowContext(r.Context(), `
				SELECT contents
				FROM blob
				WHERE sha = $1;
			`, id)
			if err := row.Scan(&data); err != nil {
				return err
			}
			_, err := w.Write(data)
			return err
		}); err != nil {
			if err == sql.ErrNoRows {
				w.WriteHeader(http.StatusNotFound)
				w.Write([]byte("Blob not found\r\n"))
				return
			} else {
				w.WriteHeader(http.StatusNotFound)
				w.Write([]byte("Blob not found\r\n"))
				return
			}
		}
	})

	gsrv.Run()
}