Skip to content

Commit

Permalink
Update repo.
Browse files Browse the repository at this point in the history
  • Loading branch information
liudng committed Apr 28, 2015
1 parent e5856ad commit 9382fda
Show file tree
Hide file tree
Showing 10 changed files with 206 additions and 209 deletions.
10 changes: 9 additions & 1 deletion .travis.yml
Original file line number Diff line number Diff line change
@@ -1 +1,9 @@
language: go
language: go
go:
- tip
before_install:
- go get github.com/axw/gocov/gocov
- go get github.com/mattn/goveralls
- if ! go get code.google.com/p/go.tools/cmd/cover; then go get golang.org/x/tools/cmd/cover; fi
script:
- $HOME/gopath/bin/goveralls -service=travis-ci
8 changes: 5 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
# web
# Web framework for golang

Golang MVC web framework.

[![Build Status](https://travis-ci.org/zhgo/web.svg)](https://travis-ci.org/zhgo/web)
[![Coverage](http://gocover.io/_badge/github.com/zhgo/web)](http://gocover.io/github.com/zhgo/web)
[![Coverage Status](https://coveralls.io/repos/zhgo/web/badge.svg)](https://coveralls.io/r/zhgo/web)
[![GoDoc](https://godoc.org/github.com/zhgo/web?status.png)](http://godoc.org/github.com/zhgo/web)
[![License](https://img.shields.io/badge/license-BSD-ff69b4.svg?style=flat)](https://github.com/zhgo/web/blob/master/LICENSE)
[![License](https://img.shields.io/badge/license-BSD-blue.svg?style=flat)](https://github.com/zhgo/web/blob/master/LICENSE)
88 changes: 39 additions & 49 deletions application.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ import (
"log"
"net/http"
"reflect"
"strconv"
"fmt"
"runtime"
)
Expand Down Expand Up @@ -61,27 +60,23 @@ type Host struct {
//action result
type Result struct {
//status
Num int64
Code int

//Message
Msg string
Err string
}

// Action load function
type actionLoadFunc func(r *Request) Result

// App
var App Application

// *http.ServeMux
var muxList = make(map[string]*http.ServeMux)

// Init
func (app *Application) Init(path string) {
// Load config file
r := map[string]string{"{WorkingDir}": kernel.WorkingDir}
config.LoadJSONFileAdv(app, path, r)

// Default Listen
if app.Listen == "" {
app.Listen = ":80"
}

// Default module
if app.Modules == nil {
app.Modules = make(map[string]Module)
Expand All @@ -90,6 +85,8 @@ func (app *Application) Init(path string) {
// Default host
if app.Hosts == nil {
app.Hosts = make(map[string]Host)
}
if _, ok := app.Hosts["Public"]; !ok {
app.Hosts["Public"] = Host{Path: "/", Root: kernel.WorkingDir + "/public"}
}

Expand Down Expand Up @@ -127,7 +124,7 @@ func (app *Application) Init(path string) {
}

// Load
func (p *Application) Load(fn actionLoadFunc) {
func (p *Application) Load(fn ActionLoadFunc) {
// hosts
for _, m := range p.Hosts {
if _, ok := muxList[m.Listen]; !ok {
Expand All @@ -150,7 +147,7 @@ func (p *Application) Load(fn actionLoadFunc) {
muxList[m.Listen] = http.NewServeMux()
}

muxList[m.Listen].HandleFunc("/"+mName+"/", newHandler(fn))
muxList[m.Listen].HandleFunc("/"+mName+"/", NewHandler(fn))
}
}

Expand All @@ -163,7 +160,7 @@ func (p *Application) Start() {
sem := make(chan int, l)

for listen, mux := range muxList {
go listenAndServe(listen, mux, sem)
go p.listenAndServe(listen, mux, sem)
}

for i := 0; i < l; i++ {
Expand All @@ -172,20 +169,30 @@ func (p *Application) Start() {
}

//new host
func listenAndServe(listen string, mux *http.ServeMux, sem chan int) {
err := http.ListenAndServe(listen, mux)
if err != nil {
log.Fatal(err)
}
func (p *Application) listenAndServe(listen string, mux *http.ServeMux, sem chan int) {
err := http.ListenAndServe(listen, mux)
if err != nil {
log.Fatal(err)
}
sem <- 0
}

// Action load function
type ActionLoadFunc func(r *Request) Result

// App
var App Application

// *http.ServeMux
var muxList = make(map[string]*http.ServeMux)

//Every request run this function
func newHandler(fn actionLoadFunc) http.HandlerFunc {
func NewHandler(fn ActionLoadFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
defer func() {
if r := recover(); r != nil {
log.Printf(r.(string))
http.Error(w, r.(string), http.StatusOK)
}
}()

Expand All @@ -194,17 +201,17 @@ func newHandler(fn actionLoadFunc) http.HandlerFunc {

cm, ok := controllers[req.Module];
if !ok {
panic(fmt.Sprintf("controller not found: %s\n", req.Module))
panic(fmt.Sprintf("Controller [%s] not found\n", req.Module))
}
controller, ok := cm[req.Controller + "Controller"]
if !ok {
panic(fmt.Sprintf("controller not found: %s::%s\n", req.Module, req.Controller))
panic(fmt.Sprintf("Controller [%s::%s] not found\n", req.Module, req.Controller))
}

//Invoke Load()
if fn != nil {
if inited := fn(req); inited.Num < 0 {
panic(fmt.Sprintf("Load falure: %s\n", inited.Msg))
if inited := fn(req); inited.Code < 0 {
panic(fmt.Sprintf("Load falure: %s\n", inited.Err))
}
}

Expand All @@ -220,51 +227,34 @@ func newHandler(fn actionLoadFunc) http.HandlerFunc {
//action
action := controller.MethodByName(method)
if action.IsValid() == false {
panic(fmt.Sprintf("method [%s] not found\n", method))
panic(fmt.Sprintf("Method [%s] not found\n", method))
}

log.Printf("method [%s] found\n", method)
log.Printf("Method [%s] found\n", method)

typ := action.Type()
numIn := typ.NumIn()
if len(req.args) < numIn {
panic(fmt.Sprintf("method [%s]'s in arguments wrong\n", method))
panic(fmt.Sprintf("Method [%s]'s in arguments wrong\n", method))
}

// Arguments
in := make([]reflect.Value, numIn)
for i := 0; i < numIn; i++ {
actionIn := typ.In(i)
kind := actionIn.Kind()
v, err := parameterConversion(req.args[i], kind)
if err != nil {
panic(fmt.Sprintf("%s's paramters error, string convert to %s failed: %s\n", method, kind, req.args[i]))
panic(fmt.Sprintf("%s paramters error, string convert to %s failed: %s\n", method, kind, req.args[i]))
}

in[i] = v
req.Args[actionIn.Name()] = v
}

// Run...
resultSli := action.Call(in)
result := resultSli[0].Interface().(Result)
view.realRender(result)
view.render(result)
}
}

// Parameter Conversion
func parameterConversion(str string, kind reflect.Kind) (reflect.Value, error) {
var v reflect.Value
var err error

switch kind {
case reflect.String:
v = reflect.ValueOf(str)
case reflect.Int64:
var i64 int64
i64, err = strconv.ParseInt(str, 10, 64)
v = reflect.ValueOf(i64)
default:
log.Printf("string convert to int failure: %s\n", str)
}

return v, err
}
8 changes: 0 additions & 8 deletions controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
package web

import (
"log"
"reflect"
)

Expand All @@ -21,13 +20,6 @@ type Controller struct {
View *View
}

//General error page
func (c *Controller) IndexErr(status int16, msg string) Result {
log.Printf("SystemIndexErr\n")

return c.View.Render()
}

//new router register
func NewController(module string, c interface{}) {
if _, ok := controllers[module]; !ok {
Expand Down
10 changes: 0 additions & 10 deletions request.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,13 +52,3 @@ func NewRequest(r *http.Request) *Request {

return &req
}

// for example: transfer browse_by_set to BrowseBySet
func pathToMethod(path string) string {
var method string
sli := strings.Split(path, "_")
for _, v := range sli {
method += strings.Title(v)
}
return method
}
42 changes: 14 additions & 28 deletions url.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,41 +9,27 @@ import (
"log"
)

func Url(m string, c string, a string, args ...interface{}) string {
module, s := App.Modules[m]
if s == false {
log.Printf("module not exists: %s\n", m)
func URL(m string, c string, a string, args ...interface{}) string {
module, ok := App.Modules[m]
if !ok {
log.Printf("Module [%s] not exists\n", m)
return ""
}

return fmt.Sprintf("http://%s/%s/%s", module.Listen, c, a)
}

func Misc(p string) string {
f, s := App.Modules["Public"]
if s == false {
log.Printf("misc file server config not exists\n")
return ""
}
str := ""
for _, v := range args {
str += fmt.Sprintf("/%v", v)
}

return fmt.Sprintf("http://%s%s", f.Listen, p)
return fmt.Sprintf("http://%s/%s/%s%s", module.Listen, c, a, str)
}

func FavUI(p string) string {
f, s := App.Modules["Public"]
if s == false {
log.Printf("FavUI config not exists\n")
func Pub(p string) string {
h, ok := App.Hosts["Public"]
if !ok {
log.Printf("Host [Public] not exists\n")
return ""
}

return fmt.Sprintf("http://%s%s", f.Listen, p)
}

func Theme(p string) string {
//theme
t := "default"

//full path
fp := fmt.Sprintf("/themes/%s%s", t, p)
return Misc(fp)
return fmt.Sprintf("http://%s%s", h.Listen, p)
}
69 changes: 69 additions & 0 deletions util.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
// Copyright 2014 The zhgo Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package web

import (
"html/template"
"log"
"reflect"
"strconv"
"strings"
"unicode"
)

//funcMap
var funcMap = template.FuncMap{
"FnURL": func(m string, c string, a string, args ...interface{}) string {
return URL(m, c, a, args...)
},
"FnPub": func(p string) string {
return Pub(p)
},
}

// for example: transfer browse_by_set to BrowseBySet
func pathToMethod(path string) string {
var method string
sli := strings.Split(path, "_")
for _, v := range sli {
method += strings.Title(v)
}
return method
}

// for example: transfer BrowseBySet to browse_by_set
func methodToPath(method string) string {
var words []string

l := 0
for s := method; s != ""; s = s[l:] {
l = strings.IndexFunc(s[1:], unicode.IsUpper) + 1
if l < 1 {
l = len(s)
}
words = append(words, strings.ToLower(s[:l]))
}

return strings.Join(words, "_")
}

// Parameter Conversion
func parameterConversion(str string, kind reflect.Kind) (reflect.Value, error) {
var v reflect.Value
var err error

switch kind {
case reflect.String:
v = reflect.ValueOf(str)
case reflect.Int64:
var i64 int64
i64, err = strconv.ParseInt(str, 10, 64)
v = reflect.ValueOf(i64)
default:
log.Printf("String convert to int failure: %s\n", str)
}

return v, err
}
8 changes: 8 additions & 0 deletions request_test.go → util_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,11 @@ func TestPathToMethod(t *testing.T) {
t.Error("pathToMethod failure")
}
}

func TestMethodToPath(t *testing.T) {
method := "BrowseBySet"
path := methodToPath(method)
if path != "browse_by_set" {
t.Errorf("methodToPath failure: %#v", path)
}
}
Loading

0 comments on commit 9382fda

Please sign in to comment.