github.com/jbking/gohan@v0.0.0-20151217002006-b41ccf1c2a96/schema/extension.go (about)

     1  // Copyright (C) 2015 NTT Innovation Institute, Inc.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //    http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
    12  // implied.
    13  // See the License for the specific language governing permissions and
    14  // limitations under the License.
    15  
    16  package schema
    17  
    18  import (
    19  	"fmt"
    20  	"net/url"
    21  	"os"
    22  	"path/filepath"
    23  	"regexp"
    24  
    25  	"github.com/cloudwan/gohan/util"
    26  )
    27  
    28  //Extension is a small plugin for gohan
    29  type Extension struct {
    30  	ID, CodeType, URL string
    31  	Code              string
    32  	Path              *regexp.Regexp
    33  }
    34  
    35  //NewExtension returns new extension from object
    36  func NewExtension(raw interface{}) (*Extension, error) {
    37  	typeData := raw.(map[string](interface{}))
    38  	extension := &Extension{}
    39  	extension.ID, _ = typeData["id"].(string)
    40  	extension.CodeType, _ = typeData["code_type"].(string)
    41  	if _, ok := typeData["url"].(string); ok {
    42  		url, err := url.Parse(typeData["url"].(string))
    43  		if err != nil {
    44  			return nil, err
    45  		}
    46  		if isURLRelative := url.Scheme == "file" && url.Host == "."; isURLRelative {
    47  			workingDirectory, err := os.Getwd()
    48  			if err != nil {
    49  				return nil, err
    50  			}
    51  			url.Host = ""
    52  			url.Path = filepath.Join(workingDirectory, url.Path)
    53  		}
    54  		extension.URL = url.String()
    55  	}
    56  	extension.Code, _ = typeData["code"].(string)
    57  
    58  	path, _ := typeData["path"].(string)
    59  	match, err := regexp.Compile(path)
    60  	if err != nil {
    61  		return nil, fmt.Errorf("failed to parse regexp: %s", err)
    62  	}
    63  
    64  	extension.Path = match
    65  	if extension.URL != "" {
    66  		remoteCode, err := util.GetContent(extension.URL)
    67  		extension.Code += string(remoteCode)
    68  		if err != nil {
    69  			return nil, fmt.Errorf("failed to load remote code: %s", err)
    70  		}
    71  	}
    72  	return extension, nil
    73  }
    74  
    75  //Match checks if this path matches for extension
    76  func (e *Extension) Match(path string) bool {
    77  	return e.Path.MatchString(path)
    78  }