This repository has been archived on 2019-06-23. You can view files and clone it, but cannot push or open issues or pull requests.
mumbledj/web.go

86 lines
1.8 KiB
Go
Raw Normal View History

2015-07-28 15:57:12 +02:00
package main
2015-07-28 15:56:20 +02:00
import (
"fmt"
"io/ioutil"
2015-07-28 17:52:53 +02:00
"math/rand"
2015-07-28 15:56:20 +02:00
"net/http"
2015-07-28 17:52:53 +02:00
"strings"
2015-07-28 17:59:55 +02:00
"time"
2015-07-28 17:32:36 +02:00
"github.com/layeh/gumble/gumble"
2015-07-28 15:56:20 +02:00
)
2015-07-28 17:59:55 +02:00
var client_token = make(map[string]string)
var token_client = make(map[string]string)
2015-07-28 17:31:37 +02:00
var external_ip = ""
2015-07-28 15:56:20 +02:00
type Page struct {
Title string
Body []byte
}
func (p *Page) save() error {
filename := p.Title + ".txt"
return ioutil.WriteFile(filename, p.Body, 0600)
}
func loadPage(title string) (*Page, error) {
filename := title + ".txt"
body, err := ioutil.ReadFile(filename)
if err != nil {
return nil, err
}
return &Page{Title: title, Body: body}, nil
}
func handler(w http.ResponseWriter, r *http.Request) {
2015-07-28 17:52:53 +02:00
var uname = token_client[r.URL.Path[1:]]
2015-07-28 18:01:10 +02:00
if uname == "" {
2015-07-28 17:52:53 +02:00
fmt.Fprintf(w, "I don't know you")
} else {
fmt.Fprintf(w, "Hi there, I love %s!", uname)
}
2015-07-28 15:56:20 +02:00
}
2015-07-28 17:31:37 +02:00
func Webserver() {
2015-07-28 15:56:20 +02:00
http.HandleFunc("/", handler)
2015-07-28 16:00:27 +02:00
http.ListenAndServe(":9563", nil)
2015-07-28 17:52:53 +02:00
rand.Seed(time.Now().UnixNano())
2015-07-28 15:56:20 +02:00
}
2015-07-28 17:31:37 +02:00
func GetWebAddress(user *gumble.User) {
2015-07-28 18:01:10 +02:00
if client_token[user.Name] != "" {
token_client[client_token[user.Name]] = ""
2015-07-28 17:52:53 +02:00
}
client_token[user.Name] = randSeq(10)
token_client[client_token[user.Name]] = user.Name
dj.SendPrivateMessage(user, fmt.Sprintf(WEB_ADDRESS, getIP(), client_token[user.Name], getIP(), client_token[user.Name]))
2015-07-28 17:31:37 +02:00
}
func getIP() string {
if external_ip != "" {
return external_ip
} else {
if response, err := http.Get("http://myexternalip.com/raw"); err == nil {
defer response.Body.Close()
if response.StatusCode == 200 {
if body, err := ioutil.ReadAll(response.Body); err == nil {
2015-07-28 17:52:53 +02:00
external_ip = strings.TrimSpace(string(body))
2015-07-28 17:31:37 +02:00
}
}
}
return external_ip
}
}
2015-07-28 17:52:53 +02:00
var letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
func randSeq(n int) string {
b := make([]rune, n)
for i := range b {
b[i] = letters[rand.Intn(len(letters))]
}
return string(b)
}