service.webfinger.go

 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
package main

import (
	"encoding/json"
	"fmt"
	"net/http"
)

type WebFingerServer struct {
	Users map[string]*User
}

type WebFingerResponse struct {
	Subject string          `json:"subject"`
	Links   []WebFingerLink `json:"links"`
}

type WebFingerLink struct {
	Rel  string `json:"rel"`
	Type string `json:"type"`
	Href string `json:"href"`
}

func (wb *WebFingerServer) Handle(w http.ResponseWriter, r *http.Request) {
	w.Header().Add("Content-Type", "application/json")
	acct := r.URL.Query().Get("resource")
	fmt.Printf("[webfinger] received request for: %v\n", acct)
	if user, exists := wb.Users[acct]; exists {
		response := WebFingerResponse{}
		response.Subject = acct
		links := []WebFingerLink{}
		links = append(links, WebFingerLink{Rel: "self", Type: "application/activity+json", Href: user.ID})
		response.Links = links
		data, _ := json.Marshal(response)
		w.Write(data)
	} else {
		fmt.Printf("[webfinger] no user found: %v\n", acct)
		w.WriteHeader(http.StatusNotFound)
	}
}