1- package main
1+ package server
22
33import (
4- "encoding/json"
54 "fmt"
5+ "github.com/DarthPestilane/aliddns/app"
6+ "github.com/DarthPestilane/aliddns/app/dns"
7+ "github.com/DarthPestilane/aliddns/app/helper"
8+ jsoniter "github.com/json-iterator/go"
69 "github.com/urfave/cli"
710 "net/http"
811 "strconv"
912)
1013
11- func cmdRun () cli.Command {
12- defaultPort , err := strconv .Atoi (env ("PORT" , "8888" ))
14+ func Command () cli.Command {
15+ defaultPort , err := strconv .Atoi (helper . Env ("PORT" , "8888" ))
1316 if err != nil {
1417 panic (fmt .Errorf ("parse env PORT failed: %v" , err ))
1518 }
@@ -24,7 +27,7 @@ func cmdRun() cli.Command {
2427 },
2528 Action : func (ctx * cli.Context ) {
2629 port := ctx .Int ("port" )
27- Log .Info (fmt .Sprintf ("listening at port %d" , port ))
30+ app . Log () .Info (fmt .Sprintf ("listening at port %d" , port ))
2831 http .HandleFunc ("/" , func (w http.ResponseWriter , r * http.Request ) {
2932 w .Header ().Set ("Content-Type" , "application/json" )
3033
@@ -35,7 +38,7 @@ func cmdRun() cli.Command {
3538 var domainName string
3639 if domains , has := query ["domain_name" ]; ! has || domains [0 ] == "" {
3740 w .WriteHeader (422 )
38- b , _ := json .Marshal (map [string ]interface {}{
41+ b , _ := jsoniter .Marshal (map [string ]interface {}{
3942 "success" : false ,
4043 "errors" : "domain_name is required" ,
4144 })
@@ -52,13 +55,13 @@ func cmdRun() cli.Command {
5255 }
5356
5457 // ip
55- currentIP := ip (r )
58+ currentIP := helper . IP (r )
5659
57- // bind
58- dns := NewDns (domainName , currentIP , rr )
59- Log .Info ("=====" )
60- if err := dns .Bind (); err != nil {
61- b , _ := json .Marshal (map [string ]interface {}{
60+ // bind dns
61+ dnsHandler := dns . New (domainName , currentIP , rr )
62+ app . Log () .Info ("=====" )
63+ if err := dnsHandler .Bind (); err != nil {
64+ b , _ := jsoniter .Marshal (map [string ]interface {}{
6265 "success" : false ,
6366 "errors" : err .Error (),
6467 })
@@ -68,18 +71,18 @@ func cmdRun() cli.Command {
6871 }
6972
7073 w .WriteHeader (200 )
71- b , err := json .Marshal (map [string ]interface {}{
74+ b , err := jsoniter .Marshal (map [string ]interface {}{
7275 "success" : true ,
7376 "message" : fmt .Sprintf ("set ip of '%s.%s' to %s" , rr , domainName , currentIP ),
7477 })
7578 if err != nil {
76- Log .Error ("decode response failed" , err )
79+ app . Log () .Error ("decode response failed" , err )
7780 return
7881 }
7982 _ , _ = w .Write (b )
8083 })
8184 if err := http .ListenAndServe (fmt .Sprintf (":%d" , port ), nil ); err != nil {
82- panic (fmt .Errorf ("start http server failed: %v " , err ))
85+ panic (fmt .Errorf ("start http server failed: %s " , err ))
8386 }
8487 },
8588 }
0 commit comments