~mendelmaleh/dummy

ref: 67121cb151871d5b36e6e29fefbfbd9c76e5b99d dummy/main.go -rw-r--r-- 2.1 KiB
67121cb1Mendel E Normalize in opt.FromForm directly 1 year, 7 months 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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
package main

import (
	"fmt"
	"html/template"
	"image/png"
	"io/ioutil"
	"log"
	"net/http"
	"net/url"
	"strings"

	"github.com/pelletier/go-toml"
)

type Config struct {
	Dummy struct {
		Addr    string
		Pattern string
	}
}

func main() {
	doc, err := ioutil.ReadFile("config.toml")
	if err != nil {
		log.Fatal(err)
	}

	config := Config{}
	err = toml.Unmarshal(doc, &config)
	if err != nil {
		log.Fatal(err)
	}

	tmpl := template.New("web").Funcs(template.FuncMap{"title": strings.Title})
	tmpl = template.Must(tmpl.Parse(`<!doctype html>
<html prefix="og: http://ogp.me/ns#">
<head>
  <title>{{ title .Name }}</title>
  <meta property="og:title" content="{{ title .Name }}" />
  <meta property="og:type" content="website" />
  <meta property="og:url" content={{ .Image }} />
  <meta property="og:image" content="{{ .Image }}" />
  <meta property="og:description" content="{{ .Desc }}" />
</head>`))

	http.HandleFunc(config.Dummy.Pattern,
		func(w http.ResponseWriter, r *http.Request) {
			Dummy(w, r, dopt.Copy())
		},
	)

	http.HandleFunc(config.Dummy.Pattern+"web/",
		func(w http.ResponseWriter, r *http.Request) {
			Web(w, r, dopt.Copy(), config, tmpl)
		},
	)

	log.Panic(http.ListenAndServe(config.Dummy.Addr, nil))
}

func Dummy(w http.ResponseWriter, r *http.Request, opt Options) {
	err := r.ParseForm()
	if err != nil {
		fmt.Fprintln(w, err)
		return
	}

	err = opt.FromForm(r.Form)
	if err != nil {
		fmt.Fprintln(w, err)
		return
	}

	im := Image(opt)
	png.Encode(w, im)

	// fmt.Fprintf(w, "%+v\n", dopt)
}

func Web(w http.ResponseWriter, r *http.Request, opt Options, config Config, tmpl *template.Template) {
	err := r.ParseForm()
	if err != nil {
		fmt.Fprintln(w, err)
		return
	}

	err = opt.FromForm(r.Form)
	if err != nil {
		fmt.Fprintln(w, err)
		return
	}

	u := url.URL{
		Host:     r.Host,
		RawQuery: r.URL.RawQuery,
		Path:     config.Dummy.Pattern,
	}

	if v, ok := r.Header["X-Forwarded-Proto"]; ok {
		u.Scheme = strings.Join(v, "")
	} else {
		u.Scheme = "http"
	}

	tmpl.Execute(w, struct {
		Name, Desc string
		Image      template.URL
	}{"Dummy", opt.Desc, template.URL(u.String())})

}