github.com/goplus/yap@v0.8.1/classfile_v2.go (about)

     1  /*
     2   * Copyright (c) 2023 The GoPlus Authors (goplus.org). All rights reserved.
     3   *
     4   * Licensed under the Apache License, Version 2.0 (the "License");
     5   * you may not use this file except in compliance with the License.
     6   * You may obtain a copy of the License at
     7   *
     8   *     http://www.apache.org/licenses/LICENSE-2.0
     9   *
    10   * Unless required by applicable law or agreed to in writing, software
    11   * distributed under the License is distributed on an "AS IS" BASIS,
    12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13   * See the License for the specific language governing permissions and
    14   * limitations under the License.
    15   */
    16  
    17  package yap
    18  
    19  import (
    20  	"reflect"
    21  	"strings"
    22  )
    23  
    24  // Handler is worker class of YAP classfile (v2).
    25  type Handler struct {
    26  	Context
    27  }
    28  
    29  // Main is required by Go+ compiler as the entry of a YAP HTTP handler.
    30  func (p *Handler) Main(ctx *Context) {
    31  	p.Context = *ctx
    32  }
    33  
    34  var (
    35  	repl = strings.NewReplacer("_", "/", "#", ":")
    36  )
    37  
    38  func parseClassfname(name string) (method, path string) {
    39  	pos := strings.IndexByte(name, '_')
    40  	if pos < 0 {
    41  		return name, "/"
    42  	}
    43  	return name[:pos], repl.Replace(name[pos:])
    44  }
    45  
    46  // AppV2 is project class of YAP classfile (v2).
    47  type AppV2 struct {
    48  	App
    49  }
    50  
    51  type iHandler interface {
    52  	Main(ctx *Context)
    53  	Classfname() string
    54  }
    55  
    56  // Gopt_AppV2_Main is required by Go+ compiler as the entry of a YAP project.
    57  func Gopt_AppV2_Main(app AppType, handlers ...iHandler) {
    58  	app.InitYap()
    59  	for _, h := range handlers {
    60  		reflect.ValueOf(h).Elem().Field(1).Set(reflect.ValueOf(app)) // (*handler).AppV2 = app
    61  		switch method, path := parseClassfname(h.Classfname()); method {
    62  		case "handle":
    63  			app.Handle(path, h.Main)
    64  		default:
    65  			app.Route(strings.ToUpper(method), path, h.Main)
    66  		}
    67  	}
    68  	if me, ok := app.(interface{ MainEntry() }); ok {
    69  		me.MainEntry()
    70  	} else {
    71  		app.Run("localhost:8080")
    72  	}
    73  }