<repo_name>forwardToday/goweb<file_sep>/minus/router.go
package minus

import (
	"fmt"
	"net/http"
	"reflect"
	"strings"
)

type controllerInfo struct {
	// regex          *regexp.Regexp
	// params         map[int]string
	controllerType reflect.Type
}

type ControllerRegistor struct {
	routers []*controllerInfo
	App     *App
}

func NewControllerRegistor() *ControllerRegistor {
	return &ControllerRegistor{}
}

func (p *ControllerRegistor) Add(pattern string, c ControllerInterface) {
	t := reflect.Indirect(reflect.ValueOf(c)).Type()
	route := &controllerInfo{}
	route.controllerType = t

	p.routers = append(p.routers, route)
}

func (app *App) SetStaticPath(url string, path string) *App {
	Mapp.StaticDirs[url] = path
	return app
}

func (p *ControllerRegistor) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	fmt.Printf("ServeHTTP:v%", p.routers)
	fmt.Printf("ServeHTTP:s%", r.Method)
	var started bool
	for prefix, staticDir := range Mapp.StaticDirs {
		if strings.HasPrefix(r.URL.Path, prefix) {
			file := staticDir + r.URL.Path[len(prefix):]
			http.ServeFile(w, r, file)
			started = true
			return
		}
	}
	// requestPath := r.URL.Path

	//find a matching Route
	for _, route := range p.routers {
		//Invoke the request handler
		vc := reflect.New(route.controllerType)
		init := vc.MethodByName("Init")
		in := make([]reflect.Value, 2)
		ct := &Context{ResponseWriter: w, Request: r}
		in[0] = reflect.ValueOf(ct)
		in[1] = reflect.ValueOf(route.controllerType.Name())
		init.Call(in)
		in = make([]reflect.Value, 0)
		method := vc.MethodByName("Prepare")
		method.Call(in)
		if r.Method == "GET" {
			fmt.Printf("GET ==============")
			method = vc.MethodByName("Get")
			method.Call(in)
		} else if r.Method == "POST" {
			method = vc.MethodByName("Post")
			method.Call(in)
		} else if r.Method == "HEAD" {
			method = vc.MethodByName("Head")
			method.Call(in)
		} else if r.Method == "DELETE" {
			method = vc.MethodByName("Delete")
			method.Call(in)
		} else if r.Method == "PUT" {
			method = vc.MethodByName("Put")
			method.Call(in)
		} else if r.Method == "PATCH" {
			method = vc.MethodByName("Patch")
			method.Call(in)
		} else if r.Method == "OPTIONS" {
			method = vc.MethodByName("Options")
			method.Call(in)
		}
		// if AutoRender {
		// 	method = vc.MethodByName("Render")
		// 	method.Call(in)
		// }
		method = vc.MethodByName("Finish")
		method.Call(in)
		started = true
		break
	}

	//if no matches to url, throw a not found exception
	if started == false {
		http.NotFound(w, r)
	}
}
<file_sep>/router/router.go
package router

import (
	"minusblog/controllers"
	"minusblog/minus"
)

func init() {
	minus.Mapp.Handlers.Add("/", &controllers.MinusController{})
}
<file_sep>/minus/context.go
package minus

import (
	"net/http"
	"net/url"
)

type Context struct {
	ResponseWriter http.ResponseWriter
	Request        *http.Request
	Multipart      bool
	Form           url.Values
}
<file_sep>/controllers/minusController.go
package controllers

import (
	"html/template"
	"minusblog/minus"
)

type MinusController struct {
	minus.Controller
}

func (c *MinusController) Get() {
	t, _ := template.ParseFiles("./view/minus.gtpl")
	t.Execute(c.Ct.ResponseWriter, nil)
	// fmt.Fprintf(c.Ct.ResponseWriter, "召唤神龙")
}
<file_sep>/minus/config.go
package minus

import (
	"time"
)

type Config struct {
	HttpAddr     string
	HttpPort     int
	TemplatePath string
	RecoverPanic bool
	RunMode      int8 //0=prod，1=dev
	UseFcgi      bool
	ReadTimeout  time.Duration // maximum duration before timing out read of the request, 默认:5*time.Second(5秒超时)
	WriteTimeout time.Duration // maximum duration before timing out write of the response, 默认:0(不超时)
}

const (
	RunModeProd int8 = 0
	RunModeDev  int8 = 1
)
<file_sep>/minus/minus.go
package minus

import (
	"fmt"
	"log"
	"net"
	"net/http"
	"net/http/fcgi"
	"os"
	"time"
)

const (
	Version = "1.0.0"
)

var (
	Mapp    *App
	AppPath string
)

func init() {
	Mapp = NewApp(nil)
	AppPath, _ = os.Getwd()
}

type App struct {
	Handlers   *ControllerRegistor
	config     *Config
	StaticDirs map[string]string
	// TemplateRegister *TemplaterRegister
}

func NewApp(config *Config) *App {
	cr := NewControllerRegistor()
	app := &App{
		Handlers:   cr,
		config:     config,
		StaticDirs: make(map[string]string),
		// TemplateRegistor: NewTemplateRegistor(),
	}
	cr.App = app
	return app
}

func (app *App) Run() {
	if app.config.HttpAddr == "" {
		app.config.HttpAddr = "192.168.127.12"
	}
	addr := fmt.Sprintf("%s:%d", app.config.HttpAddr, app.config.HttpPort)
	var err error

	// err = httpListenAndServe(addr, app.Handlers, app.config.ReadTimeout, app.config.WriteTimeout)

	for {
		if app.config.UseFcgi {
			l, e := net.Listen("tcp", addr)
			if e != nil {
				log.Print("Listen: ", e)
			}
			//log.Print("UseFcgi, fcgi.Serve")
			err = fcgi.Serve(l, app.Handlers)
		} else {
			//log.Print("http.ListenAndServe")
			//err = http.ListenAndServe(addr, app.Handlers)
			err = httpListenAndServe(addr, app.Handlers, app.config.ReadTimeout, app.config.WriteTimeout)
		}
		if err != nil {
			log.Print("ListenAndServe: ", err)
			//panic(err)
		}
		time.Sleep(time.Second * 2)
	}
}

func httpListenAndServe(addr string, handler http.Handler, readTimeout time.Duration, writeTimeout time.Duration) error {
	if readTimeout == 0 {
		readTimeout = 5 * time.Second
	}

	server := &http.Server{
		Addr:         addr,
		Handler:      handler,
		ReadTimeout:  readTimeout,
		WriteTimeout: writeTimeout,
	}

	return server.ListenAndServe()
}

func Run(config *Config) {
	Mapp.config = config
	Mapp.Run()
}
<file_sep>/main.go
package main

import (
	"fmt"
	"minusblog/minus"
	_ "minusblog/router"
	"time"
)

func main() {
	fmt.Print("main")

	config := &minus.Config{
		HttpAddr:     "localhost",
		HttpPort:     9090,
		ReadTimeout:  10 * time.Second,
		WriteTimeout: 10 * time.Second,
	}
	minus.Run(config)
}
<file_sep>/minus/template.go
package minus

import ()

// type TemplaterRegister struct {
// }
