Skip to content

Instantly share code, notes, and snippets.

@yosida95
Created December 10, 2019 11:07
Show Gist options
  • Save yosida95/bba384f6dd141caf6b0f1ca9b1c35a1e to your computer and use it in GitHub Desktop.
Save yosida95/bba384f6dd141caf6b0f1ca9b1c35a1e to your computer and use it in GitHub Desktop.
package main
import (
"encoding/json"
"flag"
"log"
"net"
"strings"
)
var socketPath string
func init() {
log.SetFlags(log.LstdFlags | log.Lshortfile)
flag.StringVar(&socketPath, "socket", "/tmp/backend.sock", "")
}
func main() {
flag.Parse()
ln, err := net.Listen("unix", socketPath)
if err != nil {
log.Fatal(err)
}
defer ln.Close()
for {
conn, err := ln.Accept()
if err != nil {
log.Println(err)
continue
}
go serve(conn)
}
}
type request struct {
Method string `json:"method"`
Parameters json.RawMessage `json:"parameters"`
}
type response struct {
Result interface{} `json:"result"`
}
type lookupRequest struct {
Qtype string `json:"qtype"`
Qname string `json:"qname"`
ZoneId int64 `json:"zone_id"`
}
type lookupResponse struct {
Qtype string `json:"qtype"`
Qname string `json:"qname"`
Content string `json:"content"`
TTL int32 `json:"ttl"`
}
func serve(conn net.Conn) {
defer conn.Close()
decoder := json.NewDecoder(conn)
encoder := json.NewEncoder(conn)
for {
var call request
if err := decoder.Decode(&call); err != nil {
log.Printf("Malformed request: %v", err)
return
}
switch strings.ToLower(call.Method) {
case "initialize":
encoder.Encode(response{
Result: true,
})
case "lookup":
var params lookupRequest
if err := json.Unmarshal(call.Parameters, &params); err != nil {
log.Printf("Malformed request: %v", err)
return
}
params.Qname = strings.ToLower(params.Qname)
var records []lookupResponse
if params.Qname == "example.com." && params.Qtype == "SOA" {
records = append(records, lookupResponse{
Qtype: params.Qtype,
Qname: "example.com",
Content: "ns.example.com. hostmaster.example.com. 1 1800 900 604800 3600",
TTL: 3600,
})
}
encoder.Encode(response{
Result: records,
})
default:
encoder.Encode(response{
Result: false,
})
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment